package wec_wallet.ebo.com.activity.main;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import bassproject.ebo.com.ebobass.activity.BaseFragment;
import bassproject.ebo.com.ebobass.http_utils.interfaces.IHttpPostListener;
import bassproject.ebo.com.ebobass.http_utils.utils.Ipost;
import bassproject.ebo.com.ebobass.http_utils.utils.NetState;
import bassproject.ebo.com.ebobass.utils.IToast;
import bassproject.ebo.com.ebobass.utils.I_Share;
import bassproject.ebo.com.ebobass.utils.Lg;
import bassproject.ebo.com.ebobass.view.CircleImageView;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;
import butterknife.Unbinder;
import wec_wallet.ebo.com.EBOApplication;
import wec_wallet.ebo.com.R;
import wec_wallet.ebo.com.activity.capital.ChangeIntoActivity;
import wec_wallet.ebo.com.activity.capital.TurnOutActivity;
import wec_wallet.ebo.com.activity.wallet.CoinDetailsActivity;
import wec_wallet.ebo.com.activity.wallet.TransferRecordsActivity;
import wec_wallet.ebo.com.adapter.WalletAdapter;
import wec_wallet.ebo.com.bean.WalletBean;
import wec_wallet.ebo.com.bean.WalletDateBean;
import wec_wallet.ebo.com.common.Constant;
import wec_wallet.ebo.com.intercept.PhoneListenService;
import wec_wallet.ebo.com.util.StringUtil;
import wec_wallet.ebo.com.utils.Functions;
import wec_wallet.ebo.com.utils.URLs;

/**
 * Created by admin on 2018/4/13.
 */

public class WalletFragment extends BaseFragment {
    @BindView(R.id.tv_wallet_total)
    TextView tvWalletTotal;
    @BindView(R.id.rela_wallet_into)
    RelativeLayout relaWalletInto;
    @BindView(R.id.rela_wallet_out)
    RelativeLayout relaWalletOut;
    @BindView(R.id.lv_wallet)
    ListView lvWallet;
    WalletAdapter adapter;
    List<WalletDateBean> list;
    EBOApplication application;
    @BindView(R.id.tv_wallet_right)
    CircleImageView tvWalletRight;
    private PhoneListenService service = null;
    private boolean isBound = false;
    private Unbinder unbinder;
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            isBound = true;
            service = ((PhoneListenService.MyBinder) binder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBound = false;
        }
    };

    public static WalletFragment newInstance() {
        WalletFragment f = new WalletFragment();
        Bundle args = new Bundle();
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle
            savedInstanceState) {
        getActivity().getWindow().setSoftInputMode
                (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN |
                        WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        View contentView = inflater.inflate(R.layout.activity_wallet, null);
        unbinder = ButterKnife.bind(this, contentView);
        initViews();
        return contentView;
    }

    public void initViews() {
        application = new EBOApplication();
        list = new ArrayList<>();
        String aPath = URLs.BASE_URL + "/" + I_Share.readAvatar();
        Lg.d(aPath);
        Picasso.get().load(aPath).into(tvWalletRight);
    }

    @OnItemClick(R.id.lv_wallet)
    public void onItemClick(int i) {
        Intent intent = new Intent(getActivity(), CoinDetailsActivity.class);
        intent.putExtra("name", list.get(i).getWallet_id());
        intent.putExtra("desc", list.get(i).getWallet_name());

        startActivity(intent);
    }

    @OnClick({R.id.rela_wallet_record, R.id.rela_wallet_01, R.id.rela_wallet_into, R.id
            .rela_wallet_out, R.id.tv_addWallet})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rela_wallet_record:
                startActivity(new Intent(getActivity(), TransferRecordsActivity.class));
                break;
            case R.id.rela_wallet_01:
                ((MainActivity) getActivity()).gotoPage(3);

                break;
            case R.id.rela_wallet_into:
                startActivity(new Intent(getActivity(), ChangeIntoActivity.class));
                break;
            case R.id.rela_wallet_out:
                startActivity(new Intent(getActivity(), TurnOutActivity.class));
                break;
            case R.id.tv_addWallet:
                ShowPopup();
                break;

        }
    }

    private void getData() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", I_Share.readAccountToken());
        map.put("uid", I_Share.readAccountUserid());

        Functions.post(getActivity(), Constant.URL_COINLIST, map, new
                ListenerProperty(), false, true);
    }

    private List<WalletDateBean> getWalletData(String json) {
        return new Gson().fromJson(json, WalletBean.class).getData();

    }


    @Override
    public void onResume() {
        super.onResume();
        getData();
        mhandle.sendEmptyMessage(1);
    }


    private class ListenerProperty implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }

        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            if (null != result) {
                try {

                    JSONObject resultObject = new JSONObject(result);
                    String status = resultObject.getString("error");
                    if (resultObject.has("is_auth") && resultObject.getString("is_auth").equals
                            ("0")) {
                        IToast.show(resultObject.getString("error_msg"));
                        Functions.relogin(getActivity());//登录过期
                        return;
                    }
                    if (resultObject.has("error_msg")) {
                        IToast.show(resultObject.getString("error_msg"));
                        return;
                    }
                    if (status.equals("0")) {
                        String count = resultObject.getString("user_count_cny");

                        tvWalletTotal.setText(count);
                        list = getWalletData(result);
                        adapter = new WalletAdapter(getActivity(), list);
                        lvWallet.setAdapter(adapter);
//                        adapter.setData(list);
//                        adapter.notifyDataSetChanged();


                    }

                } catch (Exception e) {
                    // TODO: handle exception
//                    IToast.show(e.toString());
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            } else {
                Lg.d("黑名单列表 result=null");

            }
        }
    }

    Handler mhandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    int time = 5;
                    sendMessageDelayed(obtainMessage(1), time * 1000);
                    if (NetState.isNetworkAvailable(getActivity())) {
                        getData();
                    }
                    break;


            }
        }
    };

    @Override
    public void onPause() {

        super.onPause();
        mhandle.removeMessages(1);
    }

    PopupWindow popupWindow;

    private void ShowPopup() {
        View popview = LayoutInflater.from(getContext()).inflate(R.layout
                .activity_add_wallet, null);
        View rootView = getActivity().findViewById(R.id.linear_wallet);
        popupWindow = new PopupWindow(popview,
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                true);
        StringUtil.setBackgroundAlpha(0.3f, getContext());
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setFocusable(true);

        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        popupWindow.showAtLocation(rootView,
                Gravity.CENTER | Gravity.CENTER, 0, 0);//在屏幕的中间位置显示
//        popupWindow.update();
        final ImageView img_close = popview
                .findViewById(R.id.img_addWallet_close);
        TextView btn1 = popview.findViewById(R.id.tv_addWallet_add);
        final EditText et_name = popview.findViewById(R.id.et_addWallet_name);
        et_name.setText(getString(R.string.wallet_name) + (list.size() + 1));
        et_name.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                return (event.getKeyCode() == KeyEvent.KEYCODE_ENTER);
            }
        });
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context
                .INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        img_close.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                //确定按钮实现的操作
                popupWindow.dismiss();
                StringUtil.setBackgroundAlpha(1f, getContext());

            }
        });
        btn1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // 取消按钮实现的操作
                if (!StringUtil.isStringEmpty(et_name.getText().toString())) {
                    getAddWallet(et_name.getText().toString());
                } else {
                    IToast.show(getString(R.string.input_notEmpty));
                }


            }
        });
        popupWindow.setOnDismissListener(new poponDismissListener());

    }

    /**
     * 添加钱包
     */
    private void getAddWallet(String name) {

        Map<String, Object> map = new HashMap<>();
        map.put("token", I_Share.readAccountToken());
        map.put("uid", I_Share.readAccountUserid());
        map.put("walletname", name);
        Functions.post(getActivity(), Constant.URL_ADDWALLET, map, new
                ListenerAddWallet(), true, true);
    }

    private class ListenerAddWallet implements IHttpPostListener {
        @Override
        public void onTimeOut() {

        }

        @Override
        public void responseSuccess(String result) {
            if (Ipost.isTimeOut(result)) {
                return;
            }
            if (null != result) {
                try {

                    JSONObject resultObject = new JSONObject(result);
                    String error = resultObject.getString("error");
                    if (resultObject.has("is_auth") && resultObject.getString("is_auth").equals
                            ("0")) {
                        IToast.show(resultObject.getString("error_msg"));
                        Functions.relogin(getActivity());//登录过期
                        return;
                    }
                    if (resultObject.has("error_msg")) {
                        IToast.show(resultObject.getString("error_msg"));
                        return;
                    }
                    if (error.equals("0")) {
                        JSONObject dataObj = new JSONObject(resultObject.getString("data"));
                        IToast.show(dataObj.getString("status"));
                        popupWindow.dismiss();
                        StringUtil.setBackgroundAlpha(1f, getContext());

                        getData();

                    }

                } catch (Exception e) {
                    // TODO: handle exception
//                    IToast.show(e.toString());
                    Lg.d(getClass() + ",接口解析异常：\n" + e.toString());
                }
            } else {
                Lg.d("黑名单列表 result=null");

            }
        }
    }

    class poponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            popupWindow.dismiss();
            StringUtil.setBackgroundAlpha(1f, getContext());
        }

    }

    // mpopupWindow和键盘同时出现和消失。
    private void popupInputMethodWindow() {

        Handler handler = new Handler();

        handler.postDelayed(new Runnable() {

            @Override

            public void run() {

                InputMethodManager imm = (InputMethodManager) getActivity()

                        .getSystemService(Context.INPUT_METHOD_SERVICE);

                if (imm.isActive()) {

                    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,

                            InputMethodManager.HIDE_NOT_ALWAYS);

                }

            }

        }, 0);
    }

    /**
     * onDestroyView中进行解绑操作
     */
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        mhandle.removeMessages(1);

    }
}
